package com.liqi.frame.comm.directive;

import com.liqi.frame.comm.Constants;
import com.liqi.frame.comm.token.TokenUtil;
import com.liqi.frame.comm.util.ShiroUtil;
import freemarker.core.Environment;
import freemarker.template.*;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 权限判断指令
 * Created by liqi on 2019/9/23 0023.
 */
@Component
public class HasPermissionDirective implements TemplateDirectiveModel {
    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        TemplateScalarModel keyTemplateScalarModel = (TemplateScalarModel)map.get("key");
        String key = keyTemplateScalarModel.getAsString();
        TemplateScalarModel htmlTemplateScalarModel = (TemplateScalarModel)map.get("html");
        String html = htmlTemplateScalarModel.getAsString();

        if (TokenUtil.isAdministrator() || ShiroUtil.getSubject().isPermitted(Constants.OPERATION_PASSKEY)) {
            environment.getOut().write(html);
            return;
        }

        String userId = TokenUtil.getUserId();
        if (ShiroUtil.getSubject().isPermitted(key)) {
            environment.getOut().write(html);
        } else {
            environment.getOut().write("");
        }
    }
}
